package com.andrew.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.omg.CORBA.PUBLIC_MEMBER;

import com.andrew.dao.BookDao;
import com.andrew.dao.impl.BookDaoImpl;
import com.andrew.entity.Book;
import com.andrew.entity.PageBean;
import com.andrew.service.BookService;
import com.andrew.util.JDBCUtils;
import com.andrew.util.UploadUtils;
import com.google.gson.Gson;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
//import com.sun.xml.internal.ws.spi.db.DatabindingProvider;

import sun.misc.BASE64Decoder;


public class BookServiceImpl implements BookService {
	private Book book=new Book();
	
	//获取一页上所有的书本信息
	@Override
	public PageBean getBooksByPage(String queryTerm, int currentPage) throws SQLException {
		BookDao dao =new BookDaoImpl();
		PageBean pageBean =new PageBean();
		
		//获取一页多少本书
		int pageSize=BookDaoImpl.pageSize;
		//获取总共多少本书
		long totalBooks = dao.getExistBooksCount(queryTerm);
		//获取总共的页数
		int totilPages=(int) (totalBooks % pageSize==0?totalBooks/pageSize : totalBooks/pageSize+1);
		if(totilPages==0) {
			totilPages=1;
		}		
		//设置当前页
		pageBean.setCurrentPage(currentPage);
		//设置一页多少书
		pageBean.setPageSize(pageSize);
		//设置当前页的书本集合
		pageBean.setList(dao.findBooksByPage(queryTerm,currentPage));
		//设置一共多少本书
		pageBean.setTotalBooks(totalBooks);
		//设置总页数
		pageBean.setTotilPages(totilPages);
		
		return pageBean;
	}

	/***
	 * 添加图书
	 * @throws IOException 
	 */
	@Override
	public void addBook(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
		BookDao dao =new BookDaoImpl();
		Book bookAdd=new Book();
//		//得到前端传值
//		
//		String bookName = req.getParameter("bookName");
//		String picture=req.getParameter("picture");//返回图片地址
//		String author=req.getParameter("author");
//		BigDecimal price=new BigDecimal(req.getParameter("price"));
//		String description=req.getParameter("description");
//		int stock=Integer.parseInt((req.getParameter("stock")));
//		String base64=req.getParameter("base64");
//	//拿到base64核心
//		String [] base=base64.split(",");
//		String imgStr=base[1];
//		System.out.println(imgStr);
		
		//上传图片，返回参数
		Map<String, String> map=null;
		try {
			map = UploadUtils.upLoadPic(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//获取参数
		String author=map.get("author");
		String bookName=map.get("bookName");
		BigDecimal price=new BigDecimal(map.get("price"));
		String description=map.get("description");
		int stock=Integer.parseInt(map.get("stock"));
		String picture=map.get("fileName");
		picture="BookPicture/"+picture;
		
		bookAdd.setAuthor(author);
		bookAdd.setBookName(bookName);
		bookAdd.setPrice(price);
		bookAdd.setDescription(description);
		bookAdd.setStock(stock);
		bookAdd.setPicture(picture);
		
//		//添加复制完的地址
//		
//		String endFilename="/Users/andrewlu/QweasBookStore/WebContent/BookPicture/"+picture;
//		//IO复制图片
//		//copyImage(picture, endFilename);
//		boolean convertToByte = ConvertToByte(imgStr,endFilename);
//		if(convertToByte) {
//			System.out.println("base64转化为图片成功");
//		}else {
//			System.out.println("base64转化为图片失败");
//		}
//		String picdb="BookPicture/"+picture;
//		//将复制后的文件地址保存到数据库中
//		book.setPicture(picdb);
		int addBook = dao.addBook(bookAdd);
		if(addBook>0) {
			resp.getWriter().write("addBookSuccess");
		}else {
			resp.getWriter().write("addBookFail");
		}	
		
	}
	
	

	@Override
	public int changeStocks(int bookId, int quantity) throws SQLException {
		BookDao bookDao=new BookDaoImpl();
		return bookDao.changeStocks(bookId, quantity);
	}

	/**
	 * 修改图书信息
	 * @throws IOException 
	 */
	@Override
	public void updateBookInfo(HttpServletRequest req,HttpServletResponse resp) throws SQLException, IOException {
		BookDao dao =new BookDaoImpl();
		Connection conn=JDBCUtils.getConn();
		int bookId=Integer.parseInt(req.getParameter("bookId"));
		String bookName=req.getParameter("bookName");
		String author=req.getParameter("author");
		BigDecimal price=new BigDecimal(req.getParameter("price"));
		String description=req.getParameter("description");
		int stock=Integer.parseInt(req.getParameter("stock"));
		System.out.println(bookName+":"+author+":"+price+":"+description+":"+stock);
		book.setBookId(bookId);
		book.setBookName(bookName);
		book.setAuthor(author);
		book.setPrice(price);
		book.setDescription(description);
		book.setStock(stock);
		int updateBookAll = dao.updateBookAll(book);
		if(updateBookAll>0) {
			resp.getWriter().write("UpdateBookInfoSuccess");
		}else {
			resp.getWriter().write("UpdateBookInfoFail");
		}
		
		
	}

	@Override
	public void queryBook(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
		BookDao dao =new BookDaoImpl();
		List<Book> queryAllBook = dao.queryAllBook();
		Gson gson =new Gson();
		String json = gson.toJson(queryAllBook).toString();
		resp.getWriter().write(json);
		System.out.println("Json:  "+json);
		System.out.println("queryAllBookSuccess!");
		
	
		
	}

	@Override
	public void ChangePictureForPicture(HttpServletRequest req, HttpServletResponse resp)
			throws SQLException, IOException {
	
		// 设置编码
		req.setCharacterEncoding("utf-8"); 
		resp.setContentType("text/html;charset=UTF-8");
		
		
		Map<String, String> map=null;
		try {
			map = UploadUtils.upLoadPic(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int bookId=Integer.parseInt(map.get("bookId"));
		String picture = map.get("fileName");
		
		
		String picdb="BookPicture/"+picture;
		//将复制后的文件地址保存到数据库中
		BookDao dao=new BookDaoImpl();
		//将复制后的文件地址保存到数据库中
		int updatePictureForBook = dao.updatePictureForBook(bookId, picdb);
		if(updatePictureForBook>0) {
			resp.getWriter().write("ChangePictureSuccess");
		}else {
			resp.getWriter().write("ChangePictureFail");
		}
		
	}

}
